<template>
  <view class="confirm-share">
    <!-- 加载状态 -->
    <view class="loading-state" v-if="loading">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 内容区域 -->
    <view v-else>
      <!-- 旅游产品信息 -->
      <view class="travel-card">
        <!-- 行程名称 -->
        <view class="tour-name">{{ travel.name }}</view>
        <view class="travel-info">
          <view class="travel-label">套餐名称</view>
          <view class="travel-field">
            {{ getSkuName(selectedSku) }}
          </view>
        </view>

        <!-- 出行日期和地点 -->
        <view class="travel-info">
          <view class="travel-label">出行时间</view>
          <view class="travel-dates travel-field">
            {{ formatDate(selectedDate.travel_date, 'YYYY年MM月DD日') }}
          </view>

          <view v-if="travel.departure_city" class="travel-field" style="padding-left: 12rpx;">
            {{  travel.departure_city }}出发
          </view>
        </view>

        <view class="travel-info">
          <view class="travel-label">购买须知</view>
          <view>
            <text class="travel-field">需商家确认</text>
            <text class="travel-dates" style="padding-left: 12rpx;">
              {{ refundDate }}前可免费退订
            </text>
          </view>
          <view class="travel-field-more" @click="openNotice">
            详情 >
          </view>
        </view>
      </view>

      <!-- 价格信息 -->
      <view class="price-info-card">
        <view class="price-header">
          <text class="price-title">价格明细</text>
        </view>
        <view class="price-details">
          <view class="price-item">
            <text class="price-label">成人价格</text>
            <text class="price-value">¥{{ selectedDate.adult_price }}</text>
          </view>
          <view class="price-item" v-if="selectedDate.child_price">
            <text class="price-label">儿童价格</text>
            <text class="price-value">¥{{ selectedDate.child_price }}</text>
          </view>
        </view>
      </view>

      <!-- 余额抵扣 -->
      <view class="balance-card">
        <view class="balance-header">
          <text class="balance-title">余额抵扣</text>
          <text class="balance-amount">可用余额: ¥{{ userInfo.balance || 0 }}</text>
        </view>
        <view class="balance-input-section">
          <text class="input-label">抵扣金额</text>
          <input class="balance-input" v-model="deductAmount" type="number" placeholder="请输入抵扣金额"
            @input="onDeductAmountInput" />
        </view>
        <view class="balance-tips">
          <text class="tip-text">* 抵扣金额不能超过可用余额和订单总价</text>
        </view>
      </view>

      <!-- 最终价格 -->
      <view class="final-price-card" v-show="false">
        <view class="final-price-item">
          <text class="final-label">订单总价</text>
          <text class="final-value">¥{{ totalPrice }}</text>
        </view>
        <view class="final-price-item" v-if="deductAmount > 0">
          <text class="final-label">余额抵扣</text>
          <text class="final-value deduct">-¥{{ deductAmount }}</text>
        </view>
        <view class="final-price-divider"></view>
        <view class="final-price-item total">
          <text class="final-label">实付金额</text>
          <text class="final-value">¥{{ finalAmount }}</text>
        </view>
      </view>

      <!-- 分销信息 -->
      <view class="distributor-info-card">
        <view class="distributor-header">
          <text class="distributor-title">经纪人信息</text>
        </view>
        <view class="distributor-content">
          <view class="distributor-item">
            <text class="distributor-label">经纪人</text>
            <text class="distributor-value">{{ userInfo.nickname || userInfo.username }}</text>
          </view>
          <!-- <view class="distributor-item">
            <text class="distributor-label">预计佣金</text>
            <text class="distributor-value commission">¥{{ selectedSku.share_price || 0 }}</text>
          </view> -->
        </view>
      </view>

      <!-- 底部操作栏 -->
      <view class="bottom-bar">
        <ZButton type="primary" @click="createShareOrder" :disabled="!canSubmit">创建代订订单</ZButton>
      </view>
    </view>
    <!-- 购买须知弹窗 -->
    <u-popup v-model="showNotice" mode="bottom" border-radius="20">
      <view class="notice-popup">
        <view class="notice-header">
          <view class="notice-title">购买须知</view>
          <view class="close-btn" @click="closeNotice">×</view>
        </view>
        <scroll-view class="notice-content" scroll-y="true">
          <view class="notice-content-item">
            <rich-text :nodes="travel.booking_notice"></rich-text>
          </view>
        </scroll-view>
      </view>
    </u-popup>
    <!-- 海报弹窗（组件） -->
    <SharePoster ref="sharePosterRef" :visible="showPosterModal" @close="closePosterModal" :posterTitle="'分享海报'"
      :cover="travel.cover || '/static/image/logo.png'" :title="travel.name" :skuName="getSkuName(selectedSku)"
      :dateText="selectedDate.travel_date" :qrcode="qrcode" :distributorName="userInfo.nickname || userInfo.username"
      :shareUrl="shareUrl" @uploaded="onPosterUploaded" />
  </view>
</template>

<script>
import ZButton from "../../components/ZButton.vue";
import SharePoster from "../../components/SharePoster.vue";
import dayjs from 'dayjs'
export default {
  components: { ZButton, SharePoster },
  data() {
    return {
      travelId: null,
      skuId: null,
      skuDateId: null,
      travel: {},
      selectedSku: {},
      selectedDate: {},
      loading: false,
      deductAmount: 0, // 抵扣金额
      maxDeductAmount: 0, // 最大可抵扣金额
      shareUrl: '', // 分享链接
      qrcode: '', // 二维码
      showPosterModal: false, // 是否显示海报弹窗
      shareOrderId: null, // 分销订单id
      showNotice: false, // 是否显示购买须知
    }
  },
  computed: {
    // 出发日期前3天免费退订
    refundDate() {
      // this.stockInfo.travel_date - 3使用dayjs
      return dayjs(this.selectedDate.travel_date).subtract(3, 'day').format('MM月DD日 18:00');
    },
    // 总价
    totalPrice() {
      if (!this.selectedDate.adult_price) return 0;
      return this.selectedDate.adult_price;
    },
    // 最终金额
    finalAmount() {
      const total = this.totalPrice;
      const deduct = parseFloat(this.deductAmount) || 0;
      return Math.max(0, total - deduct);
    },
    // 是否可以提交
    canSubmit() {
      return this.travelId && this.skuId && this.skuDateId && this.finalAmount > 0;
    }
  },
  onLoad(options) {
    this.$store.dispatch('getUserInfo')
    console.log('分销确认页面加载，参数:', options);

    if (options.travelId) {
      this.travelId = parseInt(options.travelId);
    }
    if (options.skuId) {
      this.skuId = parseInt(options.skuId);
    }
    if (options.skuDateId) {
      this.skuDateId = parseInt(options.skuDateId);
    }

    this.loadData();
  },
  methods: {
    // 加载数据
    loadData() {
      this.loading = true;

      // 并行加载旅游详情和库存信息
      Promise.all([
        this.loadTravelDetail(),
        this.loadSkuDetail(),
        this.loadSkuStockInfo()
      ]).then(() => {
        this.calculateMaxDeductAmount();
      }).finally(() => {
        this.loading = false;
      });
    },

    // 加载旅游详情
    loadTravelDetail() {
      return this.$api.getTravelDetail(this.travelId).then(result => {
        console.log('旅游详情:', result);
        this.travel = result || {};
      });
    },
    loadSkuDetail() {
      return this.$api.getTravelSkuDetail(this.skuId).then(result => {
        console.log('SKU详情:', result);
        this.selectedSku = result || {};
      });
    },
    // 加载SKU库存信息
    loadSkuStockInfo() {
      return this.$api.getTravelSkuStock(this.skuDateId).then(result => {
        console.log('SKU库存列表:', result);
        this.selectedDate = result || {};
      });
    },

    // 获取SKU名称
    getSkuName(sku) {
      console.log('sku', sku);
      if (!sku || !sku.spec_combination) return '';

      try {
        const specCombination = JSON.parse(sku.spec_combination);
        const specNames = Object.values(specCombination).map(value => value.replace(/,/g, '|'));
        return specNames.join(' | ');
      } catch (error) {
        console.error('解析SKU规格失败:', error);
        return '';
      }
    },

    // 计算最大可抵扣金额
    calculateMaxDeductAmount() {
      const userBalance = this.userInfo.balance || 0;
      const totalPrice = this.totalPrice;
      //   this.maxDeductAmount = Math.min(userBalance, totalPrice);
      this.maxDeductAmount = userBalance
    },

    // 抵扣金额输入处理
    onDeductAmountInput(e) {
      let value = parseFloat(e.detail.value) || 0;

      // 限制最大抵扣金额
      if (value > this.maxDeductAmount) {
        value = this.maxDeductAmount;
        this.deductAmount = value;
        uni.showToast({
          title: `抵扣金额不能超过¥${this.maxDeductAmount}`,
          icon: 'none'
        });
      }

      // 限制不能为负数
      if (value < 0) {
        value = 0;
        this.deductAmount = value;
      }
    },

    // 创建分销订单
    createShareOrder() {
      if (!this.canSubmit) {
        uni.showToast({
          title: '请完善订单信息',
          icon: 'none'
        });
        return;
      }
      this.shareOrderId = null;
      this.shareUrl = '';
      this.qrcode = '';
      uni.showLoading({
        title: '创建中...'
      });
      const orderData = {
        distributor_id: this.userInfo.id,
        travel_id: this.travelId,
        travel_sku_id: this.skuId,
        travel_sku_stock_id: this.skuDateId,
        prepay_amount: this.deductAmount,
      };

      console.log('创建分销订单:', orderData);

      this.$api.createTravelShareOrder(orderData).then(result => {
        console.log('分销订单创建成功:', result);
        this.shareOrderId = result.id;
        // 根据返回的id形成分享链接以及qrcode二维码保存，
        this.shareUrl = `/pages/travelOrder/shareOrder?id=${result.id}`;
        this.qrcode = result.qrcode;

        // 显示海报弹窗并生成海报
        this.showPosterModal = true;
        this.$nextTick(() => {
          if (this.$refs.sharePosterRef && this.$refs.sharePosterRef.generatePoster) {
            this.$refs.sharePosterRef.generatePoster(false);
          }
        });
        uni.hideLoading();
      }).catch(error => {
        console.error('创建分销订单失败:', error);
      });
    },

    // 关闭海报弹窗
    closePosterModal() {
      this.showPosterModal = false;
      // 返回上一页
      uni.navigateBack();
    },

    // 组件上传完成回调：更新分销订单的海报 URL
    onPosterUploaded(url) {
      if (!this.shareOrderId || !url) return;
      this.$api.updateTravelShareOrder(this.shareOrderId, { share_image_url: url })
        .then(res => {
          console.log('更新分销海报成功:', res);
        })
        .catch(err => {
          console.error('更新分销海报失败:', err);
        });
    },
    openNotice() {
      this.showNotice = true;
    },

    closeNotice() {
      this.showNotice = false;
    }
  },
  onShareAppMessage(res) {
    return {
      title: `【${this.userInfo.nickname}】邀请你一起旅行`,
      path: this.shareUrl
    }
  }
}
</script>

<style lang="scss">
.confirm-share {
  background-color: #f5f5f5;
  padding-bottom: 120rpx;

  /* 购买须知弹窗样式 */
  .notice-popup {
    display: flex;
    flex-direction: column;


    .notice-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      border-bottom: 1rpx solid #f0f0f0;
    }

    .close-btn {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 60rpx;
      color: #999999;
    }
    .notice-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333333;
    }

    .notice-content {
      width: 100%;
      height: 70vh;
      overflow: hidden;
      box-sizing: border-box;

      .notice-content-item {
        padding: 30rpx;
      }
    }

    .notice-item {
      margin-bottom: 30rpx;
    }

    .notice-item:last-child {
      margin-bottom: 0;
    }

    .notice-label {
      font-size: 28rpx;
      color: #333333;
      font-weight: bold;
      margin-bottom: 15rpx;
    }

    .notice-text {
      font-size: 26rpx;
      color: #666666;
      line-height: 1.5;
    }
  }

  // 旅游产品信息卡片

  .travel-card {
    background-color: #ffffff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;

    .travel-info {
      display: flex;
      align-items: center;
      padding: 4rpx 0;

      .travel-field-more {
        flex-grow: 1;
        text-align: right;
        font-size: 24rpx;
        color: #333
      }

      .travel-label {
        font-size: 24rpx;
        color: #333333;
        padding-right: 20rpx;
      }

      .travel-field {
        font-size: 24rpx;
        color: #666;
      }

      .travel-dates {
        font-size: 24rpx;
        color: #FFC300;
      }
    }
  }

  // 价格信息卡片
  .price-info-card {
    background: #FFFFFF;
    padding: 32rpx;
    margin-bottom: 24rpx;

    .price-header {
      margin-bottom: 24rpx;

      .price-title {
        font-size: 32rpx;
        color: #333333;
        font-weight: bold;
      }
    }

    .price-details {
      .price-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16rpx;

        &.total {
          margin-top: 16rpx;
          padding-top: 16rpx;
          border-top: 1rpx solid #f0f0f0;

          .price-label,
          .price-value {
            font-weight: bold;
            font-size: 32rpx;
          }
        }

        .price-label {
          font-size: 28rpx;
          color: #666666;
        }

        .price-value {
          font-size: 28rpx;
          color: #333333;
        }
      }

      .price-divider {
        height: 1rpx;
        background: #f0f0f0;
        margin: 16rpx 0;
      }
    }
  }

  // 余额抵扣卡片
  .balance-card {
    background: #FFFFFF;
    padding: 32rpx;
    margin-bottom: 24rpx;

    .balance-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24rpx;

      .balance-title {
        font-size: 32rpx;
        color: #333333;
        font-weight: bold;
      }

      .balance-amount {
        font-size: 28rpx;
        color: #ff6b35;
        font-weight: bold;
      }
    }

    .balance-input-section {
      margin-bottom: 16rpx;

      .input-label {
        font-size: 28rpx;
        color: #666666;
        margin-bottom: 12rpx;
        display: block;
      }

      .balance-input {
        width: 100%;
        height: 80rpx;
        border: 2rpx solid #e0e0e0;
        border-radius: 12rpx;
        padding: 0 24rpx;
        font-size: 28rpx;
        color: #333333;
        background: #f8f8f8;

        &:focus {
          border-color: #ff6b35;
          background: #FFFFFF;
        }
      }
    }

    .balance-tips {
      .tip-text {
        font-size: 24rpx;
        color: #999999;
      }
    }
  }

  // 最终价格卡片
  .final-price-card {
    background: #FFFFFF;
    padding: 32rpx;
    margin-bottom: 24rpx;

    .final-price-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16rpx;

      &.total {
        margin-top: 16rpx;
        padding-top: 16rpx;
        border-top: 1rpx solid #f0f0f0;

        .final-label,
        .final-value {
          font-weight: bold;
          font-size: 36rpx;
          color: #ff6b35;
        }
      }

      .final-label {
        font-size: 28rpx;
        color: #666666;
      }

      .final-value {
        font-size: 28rpx;
        color: #333333;

        &.deduct {
          color: #52c41a;
        }
      }
    }

    .final-price-divider {
      height: 1rpx;
      background: #f0f0f0;
      margin: 16rpx 0;
    }
  }

  // 分销信息卡片
  .distributor-info-card {
    background: #FFFFFF;
    padding: 32rpx;
    margin-bottom: 24rpx;

    .distributor-header {
      margin-bottom: 24rpx;

      .distributor-title {
        font-size: 32rpx;
        color: #333333;
        font-weight: bold;
      }
    }

    .distributor-content {
      .distributor-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16rpx;

        .distributor-label {
          font-size: 28rpx;
          color: #666666;
        }

        .distributor-value {
          font-size: 28rpx;
          color: #333333;

          &.commission {
            color: #ff6b35;
            font-weight: bold;
          }
        }
      }
    }
  }

  // 加载状态
  .loading-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh;
    background: #f5f5f5;

    .loading-spinner {
      width: 60rpx;
      height: 60rpx;
      border: 4rpx solid #f3f3f3;
      border-top: 4rpx solid #FFC300;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 24rpx;
    }

    .loading-text {
      font-size: 28rpx;
      color: #666666;
    }
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }

    100% {
      transform: rotate(360deg);
    }
  }

  // 底部操作栏
  .bottom-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #FFFFFF;
    padding: 24rpx 32rpx;
    border-top: 1rpx solid #f0f0f0;
    padding-bottom: 60rpx;
    z-index: 100;
  }

  // 海报弹窗
  .poster-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.6);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;

    .poster-container {
      width: 640rpx; // 320px
      height: 1000rpx; // 500px
      background: #FFFFFF;
      border-radius: 24rpx;
      overflow: hidden;
      position: relative;

      .poster-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 32rpx;
        border-bottom: 1rpx solid #f0f0f0;

        .poster-title {
          font-size: 32rpx;
          color: #333333;
          font-weight: bold;
        }

        .close-btn {
          width: 60rpx;
          height: 60rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 50%;
          background: #f5f5f5;

          .close-icon {
            font-size: 40rpx;
            color: #666666;
            line-height: 1;
          }
        }
      }

      .poster-content {
        height: calc(100% - 124rpx); // 减去header高度
        display: flex;
        flex-direction: column;

        .poster-main {
          flex: 1;
          display: flex;
          flex-direction: column;

          .poster-image-section {
            width: 100%;
            height: 480rpx; // 240px

            .poster-image {
              width: 100%;
              height: 100%;
            }
          }

          .poster-info-section {
            flex: 1;
            padding: 32rpx;
            display: flex;
            align-items: center;
            gap: 32rpx;

            .poster-details {
              flex: 1;
              display: flex;
              flex-direction: column;
              gap: 16rpx;

              .poster-travel-name {
                font-size: 28rpx; // 14px
                color: #333333;
                font-weight: bold;
                line-height: 1.4;
                display: -webkit-box;
                -webkit-box-orient: vertical;
                -webkit-line-clamp: 2;
                overflow: hidden;
              }

              .poster-sku-name {
                font-size: 18rpx; // 12px
                color: #666666;
                line-height: 1.4;
              }

              .poster-date {
                font-size: 16rpx; // 12px
                color: #999999;
              }
            }

            .poster-qrcode {
              display: flex;
              flex-direction: column;
              align-items: center;
              gap: 16rpx;

              .qrcode-image {
                width: 120rpx; // 60px
                height: 120rpx; // 60px
                border-radius: 12rpx;
                border: 2rpx solid #f0f0f0;
              }

              .qrcode-tip {
                font-size: 24rpx;
                color: #999999;
                text-align: center;
              }
            }
          }
        }

        .poster-actions {
          padding: 32rpx;
          display: flex;
          gap: 24rpx;
          border-top: 1rpx solid #f0f0f0;

          .save-poster-btn,
          .share-btn {
            flex: 1;
            height: 64rpx;
            border-radius: 32rpx;
            font-size: 24rpx;
            font-weight: bold;
            border: none;
            display: flex;
            align-items: center;
            justify-content: center;
          }

          .save-poster-btn {
            background: #f5f5f5;
            color: #666666;

            &:active {
              background: #e0e0e0;
            }
          }

          .share-btn {
            background: #ff6b35;
            color: #FFFFFF;

            &:active {
              background: #e55a2b;
            }
          }
        }
      }
    }
  }
}
</style>
